//
//  ViewController.m
//  linlee-iot-ios
//
//  Created by mengze on 2025/5/10.
//

#import "BlueDeviceListController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BluBusiness.h"
#import "BlueDeviceItem.h"
#import "Masonry.h"
#import "UIColor+Hex.h"
#import "WifiConnectionController.h"

//#import <ifaddrs.h>
//#import <arpa/inet.h>
//#import <SystemConfiguration/CaptiveNetwork.h>


#import <CoreLocation/CLLocationManager.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <SystemConfiguration/CaptiveNetwork.h>

@interface BlueDeviceListController ()<BLUBusinesP,UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate>

@property( nonatomic, strong ) UILabel * label;
@property ( nonatomic, strong ) NSMutableArray * list;
@property ( nonatomic, strong ) UITableView * tableView;
@property ( nonatomic, strong ) CLLocationManager * locManager;
@property ( nonatomic, strong ) UIView * mainView;

@property ( nonatomic, assign ) CGFloat statusBarHeight;


@end

@implementation BlueDeviceListController

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusAuthorizedAlways) {
        //再重新获取ssid
        [self getWifiName];
    }
}

- (void)alertMy{
       //1.创建UIAlertControler
       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"app需要获取您的位置权限，以获取wifi信息，给机器人配网" preferredStyle:UIAlertControllerStyleAlert];
     
       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           //使用下面接口可以打开当前应用的设置页面
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
           NSLog(@"点击了确认按钮");
       }];
       //2.2 取消按钮
       UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           NSLog(@"点击了取消按钮");
       }];
    
       //3.将动作按钮 添加到控制器中
       [alert addAction:conform];
       [alert addAction:cancel];
       
       //4.显示弹框
       [self presentViewController:alert animated:YES completion:nil];
}



- ( id ) getWifiName  {
    
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
      CGFloat version = [phoneVersion floatValue];
      // 如果是iOS13 未开启地理位置权限 需要提示一下
      if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && version >= 13) {
          NSLog(@"版本在 13 以上～～～～～");
        self.locManager = [[CLLocationManager alloc] init];
        [self.locManager requestWhenInUseAuthorization];
      }
    
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    NSLog(@"info: %@", ifs);
     id info = nil;
     for (NSString *ifnam in ifs) {
         info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
    
         if (info && [info count]) {
             break;
         }
     }
    return info;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // Objective-C获取状态栏高度
    self.statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    
    self.mainView = [[UIView alloc] init];
    [ self.mainView  setBackgroundColor:[UIColor colorWithHexString:@"ffffff"]];
    self.mainView .translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview: self.mainView ];
     
    UILayoutGuide *safeArea = self.view.safeAreaLayoutGuide;
    NSLayoutConstraint *topConstraint = [ self.mainView.topAnchor constraintEqualToAnchor:safeArea.topAnchor];
    NSLayoutConstraint *bottomConstraint = [ self.mainView.bottomAnchor constraintEqualToAnchor:safeArea.bottomAnchor];
    NSLayoutConstraint *leadingConstraint = [ self.mainView.leadingAnchor constraintEqualToAnchor:safeArea.leadingAnchor];
    NSLayoutConstraint *trailingConstraint = [ self.mainView.trailingAnchor constraintEqualToAnchor:safeArea.trailingAnchor];
    [NSLayoutConstraint activateConstraints:@[topConstraint, bottomConstraint, leadingConstraint, trailingConstraint]];

    
    
   self.locManager = [[CLLocationManager alloc] init];
   NSString * wifiName = [self getWifiName][@"SSID"];
   NSLog(@"wifiName: %@", wifiName);
    
    NSLog(@"hello world!!!");
    self.list = [[NSMutableArray alloc] init];
    self.navigationItem.backButtonTitle = @"返回";
    [self.navigationItem setTitle:@"可用蓝牙设备列表"];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"#fff"]];
    
    [self initView];
    [self initViewData];
    
    [self.tableView setBackgroundColor:[UIColor colorWithHexString:@"ffffff"]];
    [[BluBusiness shared] startWithPageName:@"BLUDeviceListController" uuid:@""];
    [BluBusiness shared].delegate = self;
    
}

- ( void ) initView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

- ( void ) initViewData {
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(0);
        make.right.mas_equalTo(self.view).offset(0);
        make.top.mas_equalTo(self.view).offset(20);
        make.bottom.mas_equalTo(self.view);
    }];
    [self.view addSubview:self.label];
    
}

- ( void ) getDeviceList:(NSArray *) list {
    
    NSLog(@"11111111111111111111111111111111111111111111111111111111");

    dispatch_async(dispatch_get_main_queue(), ^{
        
        // 你的代码
        NSLog(@"BLUDeviceList:1111111===>  %ld", list.count);
        if( list == NULL ){
            return;
        }
        
        NSLog(@"list: %@", list);
        
        NSMutableArray *identifiersInA = [NSMutableArray array];
        // 提取listA中所有设备的identifier
        for (CBPeripheral *peripheral in  self.list ) {
            [identifiersInA addObject:peripheral.identifier.UUIDString];
        }
        
        // 遍历listB，只添加不重复的设备
        for (CBPeripheral *peripheral in list) {
            NSString *currentID = peripheral.identifier.UUIDString;
            if (![identifiersInA containsObject:currentID]) {
                [self.list addObject:peripheral];
            }
        }

        [self.tableView reloadData];
    });

}


//下面三个函数是必须要实现的协议函数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSLog(@"list length: %ld", [self.list count]);
    return [self.list count];
}


// 设置数据视图的组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
 { return 10;}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}


//创建单元格对象函数
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* cellStr = @"cell";
    BlueDeviceItem * cell = (BlueDeviceItem *)[self.tableView dequeueReusableCellWithIdentifier:cellStr];
    if (cell == nil) {
        //创建一个单元格对象
        //参数一：单元格样式
        //参数二：单元格的复用标记
//        IndexTableCell

        cell = [[BlueDeviceItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.layer.masksToBounds = YES;
//        cell.layer.borderWidth = 6;
//        cell.layer.borderColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1].CGColor;

    }
    
    CBPeripheral * itemData = (CBPeripheral *)self.list[indexPath.row];
    NSString * title = [itemData name];
    NSLog(@"CBPeripheral: ");
    NSLog(@"peripheral: %@", [itemData name]);
    [cell startWithTitle: title row:indexPath.row delete:self];
    [cell setBackgroundColor:UIColor.whiteColor];
    return  cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 获取被点击的行
//    NSInteger row = indexPath.row;
//    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 取消选中
//    NSDictionary * item = [self.list objectAtIndex: (NSInteger) row];
    
    NSLog(@"点击了tableCell： %ld", indexPath.row);
}



-(void)bluDidDisconnect
{
    dispatch_async(dispatch_get_main_queue(), ^{
//        self.statusLabel.text = @"已断开与设备的连接, 正在重新扫描可用设备";
        NSLog(@"已断开与设备的连接, 正在重新扫描可用设备");
        [[BluBusiness shared] startWithPageName:@"BLUDeviceListController" uuid:@""];
    });
}


-(void)bluDidReceiveMsg:(NSString*)msg
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"msg: %@", msg);
//        self.statusLabel.text = msg;
    });
}


-(void)bluDidReceiveRealTimeReport:(uint8_t)highPress
                          lowPress:(uint8_t)lowPress
                         heartBeat:(uint8_t)heartBeat
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
        NSLog(@"@(highPress).stringValue: %@", @(highPress).stringValue);
        NSLog(@"@(highPress).stringValue: %@", @(lowPress).stringValue);
        
    });

}


-(void)bluDidReceiveCalcResult:(uint8_t)highPress
                      lowPress:(uint8_t)lowPress
                     heartBeat:(uint8_t)heartBeat
{
    
}



-(void)bluDidReceiveCalcFailResult:(NSString*)errMsg
{
    
}


- ( void ) toWifiConnectionPage {
    WifiConnectionController * vc = [[WifiConnectionController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- ( void ) btnDidClickWithType: (NSInteger) row {
    
    NSLog(@"开始进行蓝牙连接~~~~");
    CBPeripheral  * peripheral = [self.list objectAtIndex:row];
    [[BluBusiness shared] connectPeripheral:peripheral];
    
    [self performSelector:@selector(toWifiConnectionPage) withObject:nil afterDelay:1.5];
    
    
    /**
            先判断设备是否已经绑定
     **/
    
//    NSString * uuid = [[BluBusiness shared] getBluDeviceId];

//
//    NSDictionary * params = @{
//        @"deviceNumber": uuid,
//        @"deviceType": [NSString stringWithFormat:@"%d", 1],
//        @"deviceModal": @"AES_U8"
//    };
//
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.label.text = @"绑定中";
//    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
//    [hud setContentColor:[UIColor whiteColor]];
//    hud.bezelView.backgroundColor = [UIColor blackColor];
//    hud.mode = MBProgressHUDModeIndeterminate;
//    hud.removeFromSuperViewOnHide = YES;
//    __unsafe_unretained typeof(self) weakSelf = self;
//    NSLog(@"isbindedDeviceWithParams params: %@", params);
//    [[ApiUserBusiness shared] isbindedDeviceWithParams:params callback:^(id  _Nullable result, NSString * _Nullable err) {
//        NSLog(@"isBind: %d %@", [result intValue], err);
//        int value = [result intValue];
//        if( value == 2 ){
////            [hud hideAnimated:TRUE];
//            [self.view showToastWithMessage:@"他人已绑定该设备,无法绑定" duration:1.5f];
//            return;
//        }else if( value == 1 ){
////            [hud hideAnimated:TRUE];
//            [self.view showToastWithMessage:@"您已经绑定过该设备" duration:1.5f];
//            [weakSelf toNextPage];
//            return;
//        }else {
//
//            NSDictionary * params = @{
//                @"deviceNumber": uuid,
//                @"deviceType": [NSString stringWithFormat:@"%d", 1],
//                @"deviceModal": @"AES_U8"
//            };
//            [[ApiUserBusiness shared] bindDeviceWithParams:params callback:^(id  _Nullable result, NSString * _Nullable err) {
//                [hud hideAnimated:TRUE];
//                if( err ){
//                    [self.view showToastWithMessage:err duration:1.5f];
//                    return;
//                }
//                [self.view showToastWithMessage:@"绑定成功" duration:1.5f];
//                [self performSelector:@selector(toNextPage) withObject:nil afterDelay:1.f];
//            }];
//        }
//
//        //开始绑定该设备
//    }];
//    NSLog(@"蓝牙开始链接。。。。。");

    
}


@end
